package org.builder.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.builder.io.Resolver;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.Unmarshaller;
import org.xml.sax.InputSource;

public class UnmarshallServiceImpl implements UnmarshallService {

	private Mapping mapping = null;

	private String mappingLocation = null;
	
//	private Log logger = LogFactory.getLog(UnmarshallServiceImpl.class);

	
	public Object unmarshall(byte[] xml,Class _class) throws Exception {
		return unmarshall(new ByteArrayInputStream(xml),_class);
	}

	public Object unmarshall(String xml,Class _class) throws Exception {
		return unmarshall(xml.getBytes(),_class);
	}

	public Object unmarshall(InputStream inputStream,Class _class) throws Exception {
		return unmarshall(new InputSource(inputStream),_class);
	}

	public Object unmarshall(InputSource inputSource,Class _class) throws Exception {
//		logger.debug("Eseguo unmarshall");
		Unmarshaller unmarshaller = new Unmarshaller(_class);
		unmarshaller.setMapping(mapping);
//		logger.debug("Mapping settato...");
		Object obj = unmarshaller.unmarshal(inputSource);
		return obj;
	}

	public void setMappingLocation(String mappingLoaction) {
		this.mappingLocation = mappingLoaction;
		mapping = new Mapping();
		try {
			mapping.loadMapping(new InputSource(Resolver.resolveFileLocation(mappingLocation)));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MappingException e) {
			e.printStackTrace();
		}
	}

	

}
